package com.tj.api.handler;

import com.fqgj.common.api.Response;
import com.fqgj.exception.common.ApplicationException;
import com.fqgj.exception.enums.MsgCodeEnum;
import com.tj.bo.common.conf.enums.BasicErrorCodeEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

/**
 * USER: cainaitao
 * Date: 2017/4/13
 * Time: 13:55
 */

@ControllerAdvice
public class ApiExceptionHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(ApiExceptionHandler.class);

    @ExceptionHandler(Exception.class)
    @ResponseStatus(value = HttpStatus.OK)
    @ResponseBody
    public Response handleAllException(Exception ex) {
        LOGGER.info("api统一报错日志", ex);
        Response response = Response.error();
        if (ex instanceof ApplicationException) {
            ApplicationException error = (ApplicationException) ex;
            response = Response.error(
                    new MsgCodeEnum() {
                        @Override
                        public Integer getCode() {
                            return error.getErrorId();
                        }

                        @Override
                        public String getMsg() {
                            return error.getMessage();
                        }
                    }
            );
            return response;
        } else {
            response = Response.error(
                    new MsgCodeEnum() {
                        @Override
                        public Integer getCode() {
                            return BasicErrorCodeEnum.INTERNAL_SERVER_ERROR.getCode();
                        }

                        @Override
                        public String getMsg() {
                            return BasicErrorCodeEnum.INTERNAL_SERVER_ERROR.getMsg();
                        }
                    }
            );
        }
        return response;
    }
}
